package com.lagou.rpc.consumer.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.concurrent.Callable;

/**
 * 1. 发送消息
 * 2. 接收消息
 */
public class RpcClientHandler extends SimpleChannelInboundHandler<String> implements Callable {

    ChannelHandlerContext content;

    String requestMessage;
    String responseMessage;

    public void setRequestMessage(String requestMessage) {
        this.requestMessage = requestMessage;
    }

    /**
     * 通道连接就绪事件
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        System.out.println("==================");
        content = ctx;
    }

    /**
     * 通道读取就绪事件
     * @param channelHandlerContext
     * @param s
     * @throws Exception
     */
    @Override
    protected synchronized void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        responseMessage = s;
        //唤醒等待的线程---有问题
        notify();
    }

    /**
     * 发送消息到服务端并接收响应
     * @return
     * @throws Exception
     */
    @Override
    public synchronized Object call() throws Exception {

        //发送具体消息
        content.writeAndFlush(requestMessage);
        wait();
        return responseMessage;
    }
}
